"""
管理员登录页面
专门用于管理员账号登录，需要先通过访问码验证
"""

import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.pages.base_page import BasePage
from ui.components.admin_access_dialog import AdminAccessDialog
from core.utils.i18n import t
from core.utils.logger import info, warning, error
from ui.styles.theme import Theme


class AdminLoginPage(BasePage):
    """管理员登录页面"""
    
    def create_widgets(self):
        # 获取主题颜色
        fg_primary = Theme.get_color('fg_primary')
        fg_tertiary = Theme.get_color('fg_tertiary')
        accent_color = Theme.get_color('accent')
        
        # 主容器 - 居中显示
        main_container = customtkinter.CTkFrame(self, fg_color="transparent")
        main_container.place(relx=0.5, rely=0.5, anchor="center")
        
        # 标题
        self.title_label = customtkinter.CTkLabel(
            main_container, 
            text=t("admin.login.title"), 
            font=("Arial", 24, "bold"),
            text_color=fg_primary,
            bg_color="transparent"
        )
        self.title_label.pack(pady=10)
        
        self.subtitle_label = customtkinter.CTkLabel(
            main_container,
            text=t("admin.login.subtitle"), 
            font=("Arial", 12),
            text_color=fg_tertiary,
            bg_color="transparent"
        )
        self.subtitle_label.pack(pady=5)
        
        # 访问码验证提示
        self.access_hint_label = customtkinter.CTkLabel(
            main_container,
            text=t("admin.login.access_hint"), 
            font=("Arial", 10, "bold"),
            text_color="#E67E22",
            bg_color="transparent"
        )
        self.access_hint_label.pack(pady=10)
        
        # 访问码验证按钮
        self.access_verify_btn = customtkinter.CTkButton(
            main_container,
            text=t("admin.login.verify_access"),
            command=self.verify_access_code,
            width=200,
            height=35,
            font=("Arial", 12),
            fg_color=accent_color,
            hover_color="#E55A2B",
            corner_radius=10
        )
        self.access_verify_btn.pack(pady=10)
        
        # 登录表单容器（初始隐藏）
        self.login_frame = customtkinter.CTkFrame(main_container, fg_color=("gray95", "gray20"))
        self.login_frame.pack(pady=20, padx=50, fill="x", ipadx=20, ipady=20)
        self.login_frame.pack_forget()  # 初始隐藏
        
        # 表单标题
        form_title = customtkinter.CTkLabel(
            self.login_frame,
            text=t("admin.login.form_title"),
            font=("Arial", 16, "bold"),
            text_color=fg_primary
        )
        form_title.pack(pady=(0, 15))
        
        # 用户名输入
        username_label = customtkinter.CTkLabel(
            self.login_frame,
            text=t("admin.login.username"),
            font=("Arial", 12)
        )
        username_label.pack(pady=(0, 5))
        
        self.username_entry = customtkinter.CTkEntry(
            self.login_frame,
            width=250,
            height=35,
            font=("Arial", 12)
        )
        self.username_entry.pack(pady=(0, 10))
        self.username_entry.focus()
        
        # 密码输入
        password_label = customtkinter.CTkLabel(
            self.login_frame,
            text=t("admin.login.password"),
            font=("Arial", 12)
        )
        password_label.pack(pady=(0, 5))
        
        # 密码输入框和可视化切换按钮
        password_frame = customtkinter.CTkFrame(self.login_frame, fg_color="transparent")
        password_frame.pack(pady=(0, 10))
        
        self.password_entry = customtkinter.CTkEntry(
            password_frame,
            width=220,
            height=35,
            show="•",
            font=("Arial", 12)
        )
        self.password_entry.pack(side="left")
        
        self.password_visible = False
        self.password_toggle_btn = customtkinter.CTkButton(
            password_frame,
            text="👁",
            width=35,
            height=35,
            font=("Arial", 12),
            command=self.toggle_password_visibility,
            fg_color="transparent",
            hover_color=("gray80", "gray30")
        )
        self.password_toggle_btn.pack(side="left", padx=5)
        
        # 记住我选项
        self.remember_me = tk.BooleanVar()
        self.remember_check = customtkinter.CTkCheckBox(
            self.login_frame,
            text=t("admin.login.remember_me"),
            variable=self.remember_me,
            font=("Arial", 11)
        )
        self.remember_check.pack(pady=10)
        
        # 绑定回车键
        self.username_entry.bind('<Return>', lambda e: self.password_entry.focus())
        self.password_entry.bind('<Return>', lambda e: self.login())
        
        # 按钮框架
        self.button_frame = customtkinter.CTkFrame(self.login_frame, fg_color="transparent")
        self.button_frame.pack(pady=20)
        
        # 登录按钮
        self.login_btn = customtkinter.CTkButton(
            self.button_frame,
            text=t("admin.login.sign_in"),
            command=self.login,
            width=150,
            height=40,
            font=("Arial", 14, "bold"),
            fg_color=accent_color,
            hover_color="#E55A2B",
            corner_radius=10
        )
        self.login_btn.pack(side="left", padx=10)
        
        # 注册按钮
        self.register_btn = customtkinter.CTkButton(
            self.button_frame,
            text=t("admin.login.create_account"),
            command=self.show_register,
            width=150,
            height=40,
            font=("Arial", 14),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=10
        )
        self.register_btn.pack(side="left", padx=10)
        
        # 底部链接
        self.bottom_frame = customtkinter.CTkFrame(main_container, fg_color="transparent")
        self.bottom_frame.pack(pady=10)
        
        # 返回欢迎页面按钮
        self.back_btn = customtkinter.CTkButton(
            self.bottom_frame,
            text=t("admin.login.back_to_welcome"),
            command=self.back_to_welcome,
            width=130,
            height=30,
            font=("Arial", 11),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=8
        )
        self.back_btn.pack(side="left", padx=5)
        
        # 创建管理员账号
        self.create_admin_label = customtkinter.CTkLabel(
            self.bottom_frame,
            text=t("admin.login.no_account"),
            font=("Arial", 11),
            text_color=fg_tertiary
        )
        self.create_admin_label.pack(side="left", padx=(20, 5))
        
        self.create_admin_btn = customtkinter.CTkButton(
            self.bottom_frame,
            text=t("admin.login.create_admin"),
            command=self.show_register,
            width=100,
            height=30,
            font=("Arial", 11),
            fg_color="transparent",
            hover_color=("gray80", "gray30"),
            text_color=("blue", "lightblue"),
            corner_radius=8
        )
        self.create_admin_btn.pack(side="left", padx=5)
    
    def toggle_password_visibility(self):
        """切换密码可见性"""
        self.password_visible = not self.password_visible
        if self.password_visible:
            self.password_entry.configure(show="")
            self.password_toggle_btn.configure(text="🔒")
        else:
            self.password_entry.configure(show="•")
            self.password_toggle_btn.configure(text="👁")
    
    def verify_access_code(self):
        """验证访问码"""
        try:
            # 显示访问码验证对话框
            dialog = AdminAccessDialog(self)
            if dialog.show():
                # 验证成功，显示登录表单
                self.access_hint_label.configure(text=t("admin.login.access_verified"))
                self.access_verify_btn.pack_forget()
                self.login_frame.pack(pady=20, padx=50, fill="x", ipadx=20, ipady=20)
                self.username_entry.focus()
                info("管理员访问码验证成功，显示登录表单")
            else:
                # 验证失败
                warning("管理员访问码验证失败")
                
        except Exception as e:
            error(f"验证访问码时发生错误: {e}")
            messagebox.showerror(t("admin.login.error"), t("admin.login.verify_error"))
    
    def login(self):
        """处理管理员登录逻辑"""
        username = self.username_entry.get().strip()
        password = self.password_entry.get()
        
        # 输入验证
        if not username or not password:
            messagebox.showwarning(t("admin.login.input_error"), t("admin.login.enter_both"))
            return
        
        if len(username) < 3:
            messagebox.showwarning(t("admin.login.input_error"), t("admin.login.username_min_length"))
            return
        
        try:
            # 尝试登录
            remember = bool(self.remember_me.get())
            self.controller.auth_service.login(username, password, remember=remember)
            
            # 检查是否为管理员
            if not self.controller.auth_service.current_user.get_role() == "admin":
                # 不是管理员，登出
                self.controller.auth_service.logout()
                messagebox.showerror(t("admin.login.access_denied"), t("admin.login.admin_only"))
                return
            
            # 登录成功
            messagebox.showinfo(t("admin.login.success"), t("admin.login.welcome_admin", username=username))
            
            # 跳转到管理员页面
            self.controller.show_page("AdminPage")
            
        except Exception as e:
            # 登录失败
            messagebox.showerror(t("admin.login.login_failed"), str(e))
            self.password_entry.delete(0, tk.END)
            self.password_entry.focus()
    
    def show_register(self):
        """跳转到管理员注册页面"""
        self.controller.show_page("AdminRegisterPage")
    
    def back_to_welcome(self):
        """返回欢迎页面"""
        self.controller.show_page("WelcomePage")
    
    def update_data(self):
        """更新页面数据（如果需要）"""
        # 清空输入框
        self.username_entry.delete(0, tk.END)
        self.password_entry.delete(0, tk.END)
        self.username_entry.focus()
        
        # 重置密码可见性
        if self.password_visible:
            self.toggle_password_visibility()
        
        # 重置界面状态
        self.access_hint_label.configure(text=t("admin.login.access_hint"))
        self.access_verify_btn.pack(pady=10)
        self.login_frame.pack_forget()
    
    def refresh_language(self):
        """刷新语言显示"""
        try:
            # 更新标题和副标题
            self.title_label.configure(text=t("admin.login.title"))
            self.subtitle_label.configure(text=t("admin.login.subtitle"))
            
            # 更新访问码相关文本
            self.access_hint_label.configure(text=t("admin.login.access_hint"))
            self.access_verify_btn.configure(text=t("admin.login.verify_access"))
            
            # 更新标签
            username_label = self.login_frame.winfo_children()[0]
            password_label = self.login_frame.winfo_children()[1]
            if isinstance(username_label, customtkinter.CTkLabel):
                username_label.configure(text=t("admin.login.username"))
            if isinstance(password_label, customtkinter.CTkLabel):
                password_label.configure(text=t("admin.login.password"))
            
            # 更新复选框
            self.remember_check.configure(text=t("admin.login.remember_me"))
            
            # 更新按钮
            self.login_btn.configure(text=t("admin.login.sign_in"))
            self.register_btn.configure(text=t("admin.login.create_account"))
            
            # 更新底部链接
            self.back_btn.configure(text=t("admin.login.back_to_welcome"))
            self.create_admin_label.configure(text=t("admin.login.no_account"))
            self.create_admin_btn.configure(text=t("admin.login.create_admin"))
            
        except Exception as e:
            from core.utils.logger import error
            error(f"Failed to refresh language in AdminLoginPage: {e}")
